package com.example.system_development.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.system_development.common.R;
import com.example.system_development.entity.User;
import com.example.system_development.service.UserService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 用户登录
     * @param request
     * @param user
     * @return
     */
    @ApiOperation(value = "用户登录")
    @PostMapping("/login")
    public R<User> login(HttpServletRequest request, @RequestBody User user) {
        //1、将页面提交的密码password进行md5加密处理
        String password = user.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        //2、根据页面提交的用户名username查询数据库
        LambdaQueryWrapper<User> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, user.getUsername());
        User one = userService.getOne(queryWrapper);

        //3、如果没有查询到则返回登录失败结果
        if (one == null) {
            return R.error("登录失败");
        }
        //4、密码对比，如果不一致则返回登录失败结果
        if (!one.getPassword().equals(password)) {
            return R.error("登录失败");
        }

        //5、查看用户状态、如果为已禁用状态，则返回员工已禁用结果
        if (one.getStatus() == 0) {
            return R.error("账号已禁用");
        }

        //6、登录成功，将用户id存入Session并返回登录成功结果
        request.getSession().setAttribute("user", one.getUserId());

        //将用户name存入Session中
        request.getSession().setAttribute("userName", one.getName());
        return R.success(one);
    }

    /**
     * 用户退出登录
     * @param request
     * @return
     */
    @ApiOperation(value = "退出登录")
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request) {
        request.getSession().removeAttribute("user");
        return R.success("退出成功");
    }

    /**
     * 新增用户
     * @param request
     * @param user
     * @return
     */
    @ApiOperation(value = "新增用户")
    @PostMapping
    public R<String> save(HttpServletRequest request, @RequestBody User user) {
        //设置初始密码为123456.需要进行md5加密
        user.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));

        //获取当前用户id,将其设置为create_user
        Integer userId = (Integer) request.getSession().getAttribute("user");
        user.setCreateUser(userId);

        /**
         * 设置账号功能实现：
         * - 账号总共8位：
         *      - 前四位为专属企业编号
         *      - 后四位为随机数
         */

        userService.save(user);
        return R.success("新增员工成功");
    }

    /**
     * 根据id修改用户信息
     * @param user
     * @return
     */
    @ApiOperation(value = "修改用户信息")
    @PutMapping
    public R<String> update(@RequestBody User user) {
        userService.updateById(user);
        return R.success("用户信息修改成功");
    }

    /**
     * 根据id查询用户信息
     * @param userId
     * @return
     */
    @ApiOperation(value = "查询用户信息")
    @GetMapping("/{userId}")
    public R<User> getById(@PathVariable Integer userId) {
        User user = userService.getById(userId);
        if (user != null) {
            return R.success(user);
        }
        return R.error("没有查到对应用户信息");
    }

    /**
     * 用户信息分页查询
     * @param page
     * @param pageSize
     * @param name
     * @param userId
     * @return
     */
    @ApiOperation(value = "用户信息分页查询")
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name, Integer userId) {
        //构建分页构造器
        Page pageInfo = new Page(page, pageSize);
        //构造条件构造器
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件
        queryWrapper.like(StringUtils.isNotEmpty(name), User::getName, name)
                .or()
                .eq(userId != null, User::getUserId, userId);
        //添加排序条件
        queryWrapper.orderByAsc(User::getUserId);
        //执行查询
        userService.page(pageInfo, queryWrapper);

        return R.success(pageInfo);
    }

    /**
     * 删除用户
     * @param userId
     * @return
     */
    @ApiOperation(value = "删除用户")
    @DeleteMapping
    public R<String> delete(Integer userId) {
        userService.removeById(userId);
        return R.success("删除用户成功");
    }
}
